export const getCssVar = (name) => {
  if (!name) return;
  if (Array.isArray(name)) return name.reduce((acc, it) => ((acc[it] = getCssVar(it)), acc), {});
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
};

export const setCssVar = (name, value) => {
  if (!name) return;
  if (Array.isArray(name)) return name.forEach((item) => setCssVar(item.name, item.value));
  document.documentElement.style.setProperty(name, value);
};

export const formatDurationTime = (mmTimeValue, showSeconds = false) => {
  // mmTimeValue: 毫秒值，完成毫秒值转成天时分秒
  if (!mmTimeValue || typeof mmTimeValue !== 'number' || mmTimeValue <= 0) return '-';
  const totalSeconds = Math.floor(mmTimeValue / 1000);
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor((totalSeconds % 86400) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  const parts = [];
  if (days > 0) parts.push(`${days}天`);
  if (hours > 0) parts.push(`${hours}小时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  if (showSeconds || parts.length === 0) parts.push(`${seconds}秒`);
  return parts.join('');
};

const loadedResources = new Set();
export const loadResource = (options) => {
  const { url, type, cb } = options;
  if (type !== 'js' && type !== 'css') throw new Error('loadResource: type must be js or css');
  if (loadedResources.has(url)) {
    typeof cb === 'function' && cb();
    return Promise.resolve();
  }
  return new Promise((resolve, reject) => {
    let tag;
    const loadCb = () => {
      loadedResources.add(url);
      resolve();
      tag.removeEventListener('load', loadCb);
      typeof cb === 'function' && cb();
    };
    const errorCb = () => {
      reject();
      tag.removeEventListener('error', errorCb);
    };
    if (type === 'js') {
      tag = document.createElement('script');
      tag.type = 'text/javascript';
      tag.src = url;
      tag.onload = loadCb;
      tag.onerror = reject;
      document.body.appendChild(tag);
    } else if (type === 'css') {
      tag = document.createElement('link');
      tag.type = 'text/css';
      tag.rel = 'stylesheet';
      tag.href = url;
      tag.onload = loadCb;
      tag.onerror = reject;
      document.head.appendChild(tag);
    }
  });
};

export const loadResourceList = (list, cb) => {
  const filteredList = list.filter((item) => !loadedResources.has(item.url));
  return Promise.all(filteredList.map((item) => loadResource({ ...item }))).then(cb);
};
